<template>
  <el-card class="setinfo">
    <template #header>
      <div class="card-header">
        <span style="font-weight: 600; font-size: 18px;cursor: pointer;" @click="()=>{router.push('/')}">查看房户信息</span>
        <span style="font-weight: 600; font-size: 18px;cursor: pointer;" @click="()=>{router.push('/setBuild')}">/分层分户</span>
        <span style="font-weight: 600; font-size: 18px;cursor: pointer;" @click="()=>{router.push('/setInfo')}">/录入信息</span>
        <el-select
          v-model="data.pickBuild"
          placeholder="请选择楼栋"
          style="float: right; width: 230px"
          @change="changeBuild"
        >
          <el-option
            v-for="item in data.buildArr"
            :key="item.id"
            :label="item.name"
            :value="item"
          />
        </el-select>
      </div>
    </template>
    <!-- 表格 -->
    <el-table :data="data.tableData" style="width: 100%" @row-click="tableClick">
      <el-table-column label="门牌号">
        <template #default="scope">
          <div style="display: flex; align-items: center; justify-content: center">
            <span style="margin-left: 10px; color: skyblue; font-weight: bold">{{
              String(scope.row.floorNum) + '0' + String(scope.row.number)
            }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="单元号">
        <template #default="scope">
          <div style="display: flex; align-items: center; justify-content: center">
            <span style="margin-left: 10px">{{ scope.row.number }}<span> 单元</span></span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="楼层" prop="floorNum">
        <template #default="scope">
          <div style="display: flex; align-items: center; justify-content: center">
            <span style="margin-left: 10px">{{ scope.row.floorNum }}楼</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)"> 编辑信息 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      v-model:current-page="data.query.pageIndex"
      :page-size="data.query.pageNum"
      :disabled="disabled"
      :background="background"
      layout="total, prev, pager, next"
      :total="data.total"
      @current-change="getHouseData"
    />
  </el-card>
  <!-- 信息编辑-遮罩弹窗 -->
  <!-- 信息编辑-遮罩弹窗 -->
  <el-dialog v-model="dialogVisible" title="编辑信息" width="40%">
    <div>
      <section class="section">
        <h3 class="title">业主信息</h3>
        <el-form :model="submitInfo" label-width="80px" class="info">
          <el-form-item label="业主姓名" style="width: 45%">
            <el-input v-model="submitInfo.ownerName"></el-input>
          </el-form-item>
          <el-form-item label="业主性别" style="width: 45%">
            <el-select v-model="submitInfo.ownerSex" placeholder="请选择">
              <el-option label="男" value="1"></el-option>
              <el-option label="女" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="身份证号" style="width: 45%">
            <el-input v-model="submitInfo.idCard"></el-input>
          </el-form-item>
          <el-form-item label="手机号码" style="width: 45%">
            <el-input v-model="submitInfo.phoneNum"></el-input>
          </el-form-item>
          <el-form-item label="业主住址" style="width: 100%">
            <el-input v-model="submitInfo.nativePlace"></el-input>
          </el-form-item>
          <el-form-item label="业主头像">
            <el-upload
              class="avatar-uploader"
              action="http://127.0.0.1:8090/api/v1/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="submitInfo.ownerImg" :src="imageUrl.ownerImg" class="avatar" />
              <el-button size="small">{{submitInfo.ownerImg?'重新上传':'上传头像'}}</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
      </section>

      <section class="section">
        <h3 class="title">房屋信息</h3>
        <el-form :model="submitInfo" label-width="80px" class="info">
          <el-form-item label="房屋类型" style="width: 45%">
            <el-input v-model="submitInfo.houseType"></el-input>
          </el-form-item>
          <el-form-item label="房屋面积" style="width: 45%">
            <el-input v-model="submitInfo.builtArea"> <template #append>㎡</template></el-input>
          </el-form-item>
          <el-form-item label="房屋朝向" style="width: 45%">
            <el-input v-model="submitInfo.orientation"></el-input>
          </el-form-item>
          <el-form-item label="物业类型" style="width: 45%">
            <el-select v-model="submitInfo.propertyType" placeholder="请选择">
              <el-option label="居民物业" value="1"></el-option>
              <el-option label="商业物业" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="房屋号码" style="width: 100%">
            <el-input v-model="submitInfo.houseAddress" disabled></el-input>
          </el-form-item>
          <el-form-item label="户型图">
            <el-upload
              class="avatar-uploader"
              action="http://127.0.0.1:8090/api/v1/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess2"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="submitInfo.houseImg" :src="imageUrl.houseImg" class="avatar" />
              <el-button size="small">{{submitInfo.houseImg?'重新上传':'上传头像'}}</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
      </section>
    </div>

    <span class="dialog-footer" style="margin-left: 80%">
      <el-button @click="()=>{dialogVisible = false}">取消</el-button>
      <el-button type="primary" @click="submitForm">提交</el-button>
    </span>
  </el-dialog>
</template>
<script setup>
import { onMounted, getCurrentInstance, reactive, onUnmounted, ref } from 'vue'
import * as Cesium from 'cesium'
import * as turf from '@turf/turf'
import { ElMessage } from 'element-plus'
import { getBuild } from '@/api/buildApi'
import { getHouse, getOneHouseInfo ,updateInfo} from '@/api/houseApi'
import { useRouter } from 'vue-router'
const router = useRouter()
// 全局变量
const { appContext } = getCurrentInstance()
const global = appContext.config.globalProperties
let viewer

// 响应数据
const data = reactive({
  buildArr: [],
  pickBuild: null,
  query: {
    pageIndex: 1,
    pageNum: 10
  },
  tableData: [],
  total: 0
})

const dialogVisible = ref(false)
const submitInfo = ref({
  builtArea: '',
  houseAddress: '',
  houseImg: '',
  houseType: '',
  id: null,
  idCard: '',
  nativePlace: '',
  orientation: '',
  ownerImg: '',
  ownerName: '',
  ownerSex: '',
  phoneNum: '',
  propertyType: ''
})
const imageUrl= ref({
  ownerImg:'',
  houseImg:''
})
let heightList = []

// 初始化下拉框选项数据
const initData = async () => {
  const res = await getBuild()
  if (res.code == 200) {
    ElMessage.success('数据请求成功')
  }
  data.buildArr = res.data
}

// 点击选项时,视角跳转、加载分层数据
const changeBuild = (item) => {
  const center = turf.center(item.polygon)
  viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(...center.geometry.coordinates, 200)
  })
  // 加载分层数据
  data.query.id = item.id
  getHouseData()
  // 清除之前的高亮户
  heightList.length &&
    heightList.forEach((item) => {
      viewer.scene.primitives.remove(item)
    })
  heightList = []
}
// 获取这栋楼的每层数据的方法封装
const getHouseData = async () => {
  const res = await getHouse(data.query)
  console.log(res, '每户数据')
  if (res.code == 200) {
    data.tableData = res.data.list
    data.total = res.data.total
  } else {
    ElMessage.error(res.message)
  }
}
// 表格行点击时，对应户高亮
const tableClick = (row) => {
  let arr = row.polygon.coordinates[0].flat()
  // 清除之前的高亮户
  heightList.length &&
    heightList.forEach((item) => {
      viewer.scene.primitives.remove(item)
    })
  heightList = []
  // 新建紧贴3DTiles的primitive
  let height, extrudedHeight
  height = row.minHeight
  extrudedHeight = row.maxHeight
  let primitive = new Cesium.ClassificationPrimitive({
    geometryInstances: new Cesium.GeometryInstance({
      geometry: new Cesium.PolygonGeometry({
        polygonHierarchy: new Cesium.PolygonHierarchy(Cesium.Cartesian3.fromDegreesArray(arr)),
        height,
        extrudedHeight
      }),
      attributes: {
        color: Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.YELLOW.withAlpha(0.8))
      }
    }),
    classificationType: Cesium.ClassificationType.CESIUM_3D_TILE
  })
  viewer.scene.primitives.add(primitive)
  heightList.push(primitive)
}
// 编辑信息
const handleEdit = async (info) => {
  // 获取住户信息
  const res = await getOneHouseInfo({
    id: info.id
  })
  console.log(res.data,'结构');
  if(res.code == 200 ){
    // 将请求数据加载到表单中
    let arr = [
  'builtArea',
  'houseImg',
  'houseType',
  'idCard',
  'nativePlace',
  'orientation',
  'ownerImg',
  'ownerName',
  'ownerSex',
  'phoneNum',
  'propertyType'
  ]
  arr.forEach((key) =>{
    submitInfo.value[key] = res.data[key]
  })
    // 计算houseAdress、id、加载头像
    submitInfo.value.houseAddress =
      info.number + '单元' + String(info.floorNum) + '0' + String(info.number)
    submitInfo.value.id = info.id // 每个住户的id都是唯一的，按照添加顺序自增
    imageUrl.value.ownerImg = 'http://127.0.0.1:8090/'+res.data.ownerImg
    imageUrl.value.houseImg = 'http://127.0.0.1:8090/'+res.data.houseImg
 
    dialogVisible.value = true
  }
  }
// 图片上传回调函数
const handleAvatarSuccess = (response) => {
  if (response.code == 200) {
    ElMessage.success('上传成功')
    submitInfo.value.ownerImg = response.data
    imageUrl.value.ownerImg = 'http://127.0.0.1:8090/'+response.data
    // console.log(imageUrl.value.ownerImg);
  }
}
const handleAvatarSuccess2 = (response) => {
  if (response.code == 200) {
    ElMessage.success('上传成功')
    submitInfo.value.houseImg = response.data
    imageUrl.value.houseImg = 'http://127.0.0.1:8090/'+response.data
  }
}

// 上传信息
async function submitForm () {
  console.log(submitInfo.value,'准备提交');
  const res = await updateInfo(submitInfo.value)
  if(res.code == 200){
    ElMessage.success('提交成功')
  dialogVisible.value = false
}
}

onMounted(() => {
  // 获取地图变量
  viewer = global.$viewer
  // 初始化数据
  initData()
})

// 销毁组件时，同时清除地图影响
onUnmounted(() => {
  // 清除之前的高亮户
  heightList.length &&
    heightList.forEach((item) => {
      viewer.scene.primitives.remove(item)
    })
  heightList = []
  // 修正分页选择器页码
  data.query.pageIndex = 1
})
</script>
<style lang="scss">
.setinfo {
  width: 30%;
  position: absolute;
  top: 4%;
  left: 4%;
  z-index: 999;
  .el-card__body {
    .el-table {
      td {
        text-align: center !important;
      }
      th {
        text-align: center !important;
      }
    }
  }
}
.el-upload-list {
  display: none !important;
}
.avatar {
  width: 50px;
  height: 50px;
}

.section {
  display: flex;
  flex-direction: column;
  padding: 0px 20px;
  h3 {
    margin: 0 auto;
    padding-bottom: 15px;
  }
  .info {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
  }
}
</style>
